<?php
/**
 * Created by PhpStorm.
 * User: sunyang
 * Date: 2017/1/21
 * Time: 10:00
 */
class IconvLib{
    var $_iconvlib=null;
    function __construct()
    {
        $this->csvbase();
    }
    public function csvbase(){
        static $lib = null;
        if($lib === null){
            include_once(ROOTPATH . '/lib/include/iconv.lib.php');
            $this->_iconvlib = new Chinese(ROOTPATH . '/lib/include/codetable/');
        }
    }
    function export_to_csv($filename, $data, $to_charset = '')
    {
        if ($to_charset && $to_charset != 'utf-8')
        {
            $need_convert = true;
        }
        else
        {
            $need_convert = false;
        }

        header("Content-type: application/unknown");
        header("Content-Disposition: attachment; filename={$filename}.csv");
        foreach ($data as $row)
        {
            foreach ($row as $key => $col)
            {

                if ($need_convert)
                {
                    $col = $this->_iconvlib->Convert('utf-8', $to_charset, $col);
                }
                $row[$key] = $this->_replace_special_char($col);

            }
            echo join(',', $row) . "\r\n";
        }
    }
    /**
     * 替换影响csv文件的字符
     *
     * @param $str string 处理字符串
     */
    function _replace_special_char($str, $replace = true)
    {
        $str = str_replace("\r\n", "", $str);
        $str = str_replace("\t", "    ", $str);
        $str = str_replace("\n", "", $str);
        if ($replace == true)
        {
            $str = '"' . str_replace('"', '""', $str) . '"';
        }
        return $str;
    }
}